﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace VTLive.Models
{
    public class UserRepository
    {
        VTliveDataContext db = new VTliveDataContext();

        public IQueryable<User> GetAllUsers()
        {
            return db.Users;
        }

        public User GetUser(int UserID)
        {
            return db.Users.SingleOrDefault(s => s.ID == UserID);
        }

        public User GetUserByUserName(string UserName)
        {
            return db.Users.SingleOrDefault(s => s.Username == UserName);
        }

        public void Add(User MyUser)
        {
            db.Users.InsertOnSubmit(MyUser);
        }

        public User Authenticate(string userName, string password)
        {
            var MyUser = (from user in db.Users where user.Username == userName && user.Password == password select user);

            return MyUser.SingleOrDefault();
        }

        public void Delete(User MyUser)
        {
            db.Users.DeleteOnSubmit(MyUser);

            var UsersStations = from station in db.Stations where station.OwnerID == MyUser.ID select station;
            db.Stations.DeleteAllOnSubmit(UsersStations);

            var UsersAssociations = from association in db.Associates where association.UserID == MyUser.ID select association;
            db.Associates.DeleteAllOnSubmit(UsersAssociations);

            var UsersSuggestions = from suggestion in db.Suggestions where suggestion.AssociateID == MyUser.ID select suggestion;
            db.Suggestions.DeleteAllOnSubmit(UsersSuggestions);
        }

        public void Save()
        {
            db.SubmitChanges();
        }
    }
}
